#include "Log.h"
#include "unistd.h"

Log::Log()
{
    logPath = "/root/home/log.txt";
}


//void Log::writeToLog(QString fileName,QString str)
void Log::writeToLog(QString fileName,QString str)
{
//#ifdef DEBUG
   // QString fn = "/root/home/Log"+fileName;
    QDir path;
    if(!path.exists("/root/home/Log"))
    {
        path.mkdir("/root/home/Log");
    }
    QString fn = "/root/home/Log/"+fileName;
    QFile file(fn);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        qDebug()<<"open log.txt fail";
        return;
    }
    QTextStream gOutStream(&file);
    QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh.mm.ss");
    gOutStream<<time+str<<"\r\n"<<endl;
    gOutStream.flush();
     fsync(file.handle());
    file.close();
//#endif

}

void Log::removeOutOfDate()
{
    QString path="/root/home/Log";
    QDir dir(path);
    QStringList filter;
    filter <<"*";
    QStringList files = dir.entryList(filter,QDir::Files|QDir::Readable,QDir::Name);
   // qDebug()<<files;
    QList<QFileInfo> *fileInfo = new QList<QFileInfo>(dir.entryInfoList(filter));
    QFileInfoList fileList = dir.entryInfoList(filter);
    foreach (QFileInfo file, fileList) {
      //  qDebug()<<file.fileName();
         QDateTime fN=QDateTime::fromString(file.fileName(),"yyyy-MM-dd");
         if(fN.isValid())
         {
            // qDebug()<<file.fileName()<<" is valid";
             uint sTime = fN.toTime_t();
             QString curtime = QDateTime::currentDateTime().toString("yyyy-MM-dd");
             QDateTime cT=QDateTime::fromString(curtime,"yyyy-MM-dd");
             uint cTime = cT.toTime_t();
             if(cTime < sTime)
             {

             }
             else
             {
                 if(cTime - sTime >=432000 )
                 {
                     file.dir().remove(file.fileName());
                 }
             }
         }
         else
         {
             // qDebug()<<file.fileName()<<" is invalid";
              file.dir().remove(file.fileName());
         }
    }



}


